package com.vagavaga.bizworld.jpatx;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import javax.persistence.EntityManager;

class ParentEntityManager extends EntityManagerInterceptor {

    private final EntityManager original;
    private final String persistenceUnitName;

    ParentEntityManager(EntityManager em, String persistenceUnitName) {
        this.original = em;
        this.persistenceUnitName = persistenceUnitName;
    }

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        if (JOIN_TRANSACTION.equals(method)) {
            throw new IllegalStateException("Illegal operation while EntityManager is handled by bizworld"); 
        }
        if (GET_TRANSACTION.equals(method)) {
            return getTransaction();
        }
        if (CLOSE.equals(method)) {
            TxManager.unbind(persistenceUnitName);
        }
        try {
            return method.invoke(original, args);
        } catch (InvocationTargetException e) {
            throw e.getTargetException();
        }
    }

    private Object getTransaction() {
        return ParentTransaction.wrap(original.getTransaction());
    }

    public static EntityManager wrap(EntityManager em, String persistenceUnitName) {
        ParentEntityManager pem = new ParentEntityManager(em, persistenceUnitName);
        return (EntityManager) Proxy.newProxyInstance(
                em.getClass().getClassLoader(),
                new Class<?>[] { EntityManager.class },
                pem);
    }

}
